package handles

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"vehicle-mgr/cache"
	"vehicle-mgr/models"
)

func CarList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	/*
		SELECT
		  cars.id AS CarId,
		  cars.car_name AS CarName,
		  cars.car_code AS CarCode,
		  cars.car_price AS CarPrice,
		  car_types.type_name AS TypeName,
		  car_types.type_comment AS TypeComment
		FROM
		  cars
		  LEFT JOIN car_types ON cars.tid = car_types.id
	*/
	var car []models.CarList
	redis_key := "carList_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("cars").
			Select(
				"cars.id AS CarId",
				"cars.car_name AS CarName",
				"cars.car_code AS CarCode",
				"cars.car_price AS CarPrice",
				"car_types.type_name AS TypeName",
				"car_types.type_comment AS TypeComment",
			).
			Joins("LEFT JOIN car_types ON cars.tid = car_types.id").
			Offset(offset).Limit(size).Find(&car)
		jsonData, _ := json.Marshal(car)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &car)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": car,
	})
	return
}

func CarDetail(c *gin.Context) {
	id := c.Query("id")
	var car models.CarList
	redis_key := "detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	/*
		SELECT
		  cars.id AS CarId,
		  cars.car_name AS CarName,
		  cars.car_code AS CarCode,
		  cars.car_price AS CarPrice,
		  car_types.type_name AS TypeName,
		  car_types.type_comment AS TypeComment
		FROM
		  cars
		  LEFT JOIN car_types ON cars.tid = car_types.id
	*/
	if cacheData == "" {
		models.DB.Table("cars").
			Select(
				"cars.id AS CarId",
				"cars.car_name AS CarName",
				"cars.car_code AS CarCode",
				"cars.car_price AS CarPrice",
				"car_types.type_name AS TypeName",
				"car_types.type_comment AS TypeComment",
			).
			Joins("LEFT JOIN car_types ON cars.tid = car_types.id").
			Where("car_types.id=?", id).Find(&car)
		jsonData, _ := json.Marshal(car)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &car)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": car,
	})
	return
}
